package com.lxu.jdbc.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCUtil {

    private static DataSource dataSource;

    static {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db_user");
            ds.setUser("root");
            ds.setPassword("123");
            //初始化
            ds.setInitialPoolSize(5);
            //设置最大的链接数
            ds.setMaxPoolSize(15);
            dataSource = ds;
        } catch (Exception e) {
        }
    }

    /**
     * 初始化数据库连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 释放资源
     *
     * @param ios
     */
    public static void release(AutoCloseable... ios) {
        for (AutoCloseable io : ios) {
            if (io != null) {
                try {
                    io.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 提交事务 并关闭连接
     *
     * @param conn
     */
    public static void commitAndClose(Connection conn) {
        try {
            conn.commit();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务  并关闭连接
     *
     * @param conn
     */
    public static void rollbackAndClose(Connection conn) {
        try {
            conn.rollback();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
